package com.jdone.compus.service;

import com.jdone.compus.utils.SignUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentNotificationService {

    private static final String SIGN_TYPE = "MD5";

    @Value("${project.mchId}")
    private  String MCH_ID;

    @Value("${project.mchKey}")

    private  String SECRET_KEY;

    @Value("${project.api.url}")
    private  String URL;

    public Map<String, Object> recharge(String telPhone, int amount, String outTradeNo) {
        try {
            // Prepare the request parameters
            Map<String, String> params = new HashMap<>();
            params.put("mchId", MCH_ID);
            params.put("signType", SIGN_TYPE);
            params.put("telPhone", telPhone);
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            params.put("amount", String.valueOf(amount));
            params.put("rechargeMode", "52");
            params.put("isGiven", "0");
            params.put("outTradeNo", outTradeNo);

            // Generate the sign
            String sign = SignUtil.generateSign(params,SECRET_KEY);
            params.put("sign", sign);

            // Prepare the headers
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // Prepare the request body
            MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
            requestBody.setAll(params);


            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(URL + "/recharge", HttpMethod.POST, requestEntity, Map.class);

            return response.getBody();

        } catch (Exception e) {
            return new HashMap<>();
        }
    }
}
